package com.wongoing.test.other;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.junit.Test;

import com.wongoing.apiclient.alipay.AlipayHelper;
import com.wongoing.apiclient.alipay.query.Alipay;
import com.wongoing.apiclient.weixin.WXPayHelper;
import com.wongoing.jwt.TokenManager;
import com.wongoing.sys.service.SysConfigService;
import com.wongoing.sys.shiro.ShiroHelper;
import com.wongoing.util.CommonUtils;
import com.wongoing.util.DateConvert;
import com.wongoing.util.manager.SmsVerCodeManager;
import com.wongoing.util.manager.SmsVerCodeManagerBean;

public class ShiroHelperTester {
	
	 private static final String KEY_ALGORITHM = "AES";
	    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默认的加密算法
	@Test
	public void testEncrypt() {
			
		try {
			String url = CommonUtils.fillZeroBeforeString("1", 5);
			System.out.println(url);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
//		SimpleDateFormat  dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); 
//		ParsePosition pos = new ParsePosition(0);
//		try {
//			Long time = dateFormat.parse("2017-05-18T10:26:10.488Z",pos).getTime();
//			
//			
//			System.out.println("pos.getIndex():"+ pos.getIndex() +"|| date.length(): "+ "2017-05-18T10:26:10.488Z".length());
//			System.out.println("dateFormat:"+DateConvert.formatStringToDate("2017-05-18T10:26:10.488Z"));
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		//		String source = "mesnac@132";
//		String algorithmName = "SHA-1";
//		String salt1 = "mesnac";
//		String salt2 = ShiroHelper.SALT2;
//		int hashIterations = 1024;
//		
//		String encode = ShiroHelper.encrypt(source, algorithmName, salt1, salt2, hashIterations);
//		System.out.println(encode);
/*		SmsVerCodeManagerBean smsBean = new SmsVerCodeManagerBean(); 
		smsBean.setMobile("123");
		smsBean.setMsgId("123456");
		
		SmsVerCodeManager.getInstance().addVerCode("123", smsBean);
		for (SmsVerCodeManagerBean bean : SmsVerCodeManager.getInstance().getAllVerCode()) {
			smsBean.setSendCount(bean.getSendCount()+1);
			System.out.println(bean.getSendCount());
			System.out.println(bean.getSendMaxCount());
		}*/
	}
	
	@Test
	public void testAEScrypt() {
		String s = encrypt("16","zpj");
		System.out.println("---》》》"+s);
	}
	
	@Test
	public void testAESdecrypt() {
		String s = decrypt("k/J4WGOoUbYw3KmMv4ZHEl==","zpj");
		System.out.println("---》》》"+s);
	}
    /**
     * AES 加密操作
     *
     * @param content 待加密内容
     * @param password 加密密码
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content, String password) {
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器

            byte[] byteContent = content.getBytes("utf-8");

            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password));// 初始化为加密模式的密码器

            byte[] result = cipher.doFinal(byteContent);// 加密

            return Base64.encodeBase64String(result);//通过Base64转码返回
        } catch (Exception ex) {
          
        }

        return null;
    }

    /**
     * AES 解密操作
     *
     * @param content
     * @param password
     * @return
     */
    public static String decrypt(String content, String password) {

        try {
            //实例化
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);

            //使用密钥初始化，设置为解密模式
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));

            //执行操作
            byte[] result = cipher.doFinal(Base64.decodeBase64(content));

            return new String(result, "utf-8");
        } catch (Exception ex) {
           
        }
        
        return null;
    }

    /**
     * 生成加密秘钥
     *
     * @return
     */
    private static SecretKeySpec getSecretKey(final String password) {
        //返回生成指定算法密钥生成器的 KeyGenerator 对象
        KeyGenerator kg = null;

        try {
            kg = KeyGenerator.getInstance(KEY_ALGORITHM);

            //AES 要求密钥长度为 128
            kg.init(128, new SecureRandom(password.getBytes()));

            //生成一个密钥
            SecretKey secretKey = kg.generateKey();

            return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥
        } catch (NoSuchAlgorithmException ex) {
            
        }

        return null;
    }
	@Test
	public void getServeSequenceTeseter(){
		
//		List<String> str = new  ArrayList<String>();
//		int count = 0;
//		for (int i = 0; i < 100000; i++) {
//			String sequence = SequenceBuilder.getInstance().getServeSequence();
//			
//			for (int j = 0; j < str.size(); j++) {
//				if(str.get(j).equals(sequence)) count++;
//			}
//			str.add(sequence);
//		
//		}
		//System.out.println(DateConvert.formatDateToDate(new Date(), DateStyle.YYYY_MM_DD_HH_MM_SS));
		//Integer i = Integer.parseInt("10");
		//System.out.println(i.compareTo(9));
		//System.out.println(ResourceUtil.getUploadImageProjectRoot());
		try {
			//System.out.println("mesnac@123".matches("(?!^[0-9]+$)(?!^[A-z]+$)(?!^[^A-z0-9]+$)^.{6,20}$"));; 
			//new Thread(new MailUtil("wu_zhaoqiang@126.com", "132456")).start();
			/*			String codeUrl = "sssss";
			String email = "wu_zhaoqiang@126.com";
			final String from = "wzhq110ok@163.com";// 发件人电子邮箱
			final String host = "smtp.163.com"; // 指定发送邮件的主机smtp.qq.com(QQ)|smtp.163.com(网易)

			Properties properties = System.getProperties();// 获取系统属性

			properties.setProperty("mail.smtp.host", host);// 设置邮件服务器
			properties.setProperty("mail.smtp.auth", "true");// 打开认证

				//QQ邮箱需要下面这段代码，163邮箱不需要
				MailSSLSocketFactory sf = new MailSSLSocketFactory();
				sf.setTrustAllHosts(true);
				properties.put("mail.smtp.ssl.enable", "true");
				properties.put("mail.smtp.ssl.socketFactory", sf);
				
				
				// 1.获取默认session对象
				Session session = Session.getDefaultInstance(properties, new Authenticator() {
					public PasswordAuthentication getPasswordAuthentication() {
						//return new PasswordAuthentication("service@yeefeipass.com", "08012093A."); // 发件人邮箱账号、授权码
						return new PasswordAuthentication(from, "zhjx725163"); // 发件人邮箱账号、授权码
					}
				});

				// 2.创建邮件对象
				Message message = new MimeMessage(session);
				// 2.1设置发件人
				message.setFrom(new InternetAddress(from));
				// 2.2设置接收人
				message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
				// 2.3设置邮件主题
				message.setSubject("邮箱激活");
				// 2.4设置邮件内容
				String content = "<html><head></head><body><h1>这是一封激活邮件,激活请点击以下链接</h1><h3>"
						+ "<a href='"+codeUrl+"'>"+codeUrl+ "</a></h3></body></html>";
				message.setContent(content, "text/html;charset=UTF-8");
				// 3.发送邮件
				Transport.send(message);
				System.out.println("邮件成功发送!");*/
//			  QuartzTest q=new QuartzTest();
/*			Alipay q = AlipayHelper.payQueryToBean("2017122921001004840244130402", "");
			System.out.println(q.getIsSuccess());
			System.out.println(q.getResponse().getTrade());*/
			/*String s=AlipayHelper.payRefund("201712290002", "2017-12-29 11:01:00", "1", "2017122921001004270267636025^0.01^航班", "");
			System.out.println(">>>>"+s);*/
	/*		Map<String,String> map = WXPayHelper.getInstance().weixinPayRefund("20171219150104015155607", "20171219150104025155607", "1","1");
			for (Map.Entry<String, String> entry : map.entrySet()) {
				            System.out.println("key= " + entry.getKey() + " and value= "
				                    + entry.getValue());
				  }*/
/*			Map<String, String> s = WXPayHelper.getInstance().weixinPayRefund("20180109010401229022", "201801090104021229022", "1", "1");
			System.out.println(s);*/
/*			String ids = "123,";
					ids= "".equals(ids)?ids:ids.substring(0, ids.length()-1);
			System.out.println(ids);*/
			//System.out.println(Thread.currentThread().getContextClassLoader().getResource("").getPath());
	
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//System.out.println(DateConvert.formatStringToDate("2017-11-15 00:00:00", DateStyle.HH_MM_SS).compareTo(DateConvert.formatDateToDate(new Date(), DateStyle.HH_MM_SS)));
		//System.out.println(SequenceBuilder.getInstance().getOrderNumByNow("01", 2, "6"));
	}
}
